<template>
	<view class="user-order-refund" style="padding-top: 1rpx;" :style="{background:pageColor}" v-if="detail.id">
		<view class="item-child mt-md ml-lg mr-lg pd-lg fill-base radius-16">
			<view class="flex-between pb-lg b-1px-b">
				<view class="f-paragraph c-title max-380 ellipsis">订单号：{{detail.order_code}}</view>
				<view class="f-caption text-bold"
					:style="{color:detail.pay_type==2?primaryColor: detail.pay_type<6?subColor: detail.pay_type == 6 ? '#11C95E' : '#333'}">
					{{statusType[detail.pay_type]}}
				</view>
			</view>
			<block v-for="(item,index) in detail.order_goods" :key="index">
				<view @tap="handerRadioChange(index)" class="item-child flex-center mt-lg"
					v-if="item.can_refund_num > 0">
					<i class="iconfont mr-md" :class="[{'icon-xuanze':!item.checked},{'icon-xuanze-fill':item.checked}]"
						:style="{color:item.checked ? primaryColor : ''}"></i>
					<view class="flex-1">
						<view class="flex-warp">
							<!-- #ifdef H5 -->
							<view class="goods-img radius-16">
								<view class="h5-image goods-img radius-16"
									:style="{ backgroundImage : `url('${item.goods_cover}')`}">
								</view>
							</view>
							<!-- #endif -->
							<!-- #ifndef H5 -->
							<image mode="aspectFill" class="goods-img radius-16" :src="item.goods_cover"></image>
							<!-- #endif -->

							<view class="flex-1 ml-md max-380">
								<view class="f-title c-title text-bold max-450 ellipsis" style="height: 44rpx;">
									{{item.goods_name}}
								</view>
								<view class="flex-y-center f-caption c-caption" style="margin: 3rpx 0;height: 34rpx;">
									{{$t('action.attendantName').substring(0, 2) === '服务' ? '' : '服务'}}{{$t('action.attendantName')}}
									<view class="ml-md">{{detail.coach_info ? detail.coach_info.coach_name : '-'}}
									</view>
								</view>
								<view class="f-caption c-caption" style="height: 34rpx;">{{detail.start_time}}</view>
								<view class="flex-between" style="margin-top:5rpx;">
									<view class="flex-y-baseline f-caption c-warning">¥<view class="f-title text-bold">
											{{item.true_price}}
										</view>
									</view>
									<view class="flex-warp" v-if="item.can_refund_num > 1">
										<button @tap.stop="changeNum(index,-1)" class="reduce"
											:style="{borderColor:primaryColor,color:primaryColor}"><i
												class="iconfont icon-jian-bold"></i></button>
										<button class="addreduce clear-btn">{{item.apply_num}}</button>
										<button @tap.stop="changeNum(index,1)" class="add"
											:style="{background:primaryColor,borderColor:primaryColor}"><i
												class="iconfont icon-jia-bold"></i></button>
									</view>
									<view class="c-paragraph" v-else>x{{item.apply_num}}</view>
								</view>

							</view>
						</view>
					</view>
				</view>
			</block>

			<view class="mt-lg pt-lg pb-lg f-paragraph c-title b-1px-t"
				v-if="detail.can_refund_car_price &&  detail.car_price*1>0 && !detail.free_fare">
				<view class="flex-between">
					<view>服务金额</view>
					<view>¥{{detail.can_refund_price}}</view>
				</view>
				<view class="flex-between mt-sm" v-if="detail.can_refund_car_price &&  detail.car_price*1>0 ">
					<view class="flex-y-baseline">车费<view class="f-icontext c-warning ml-sm">
							{{$t('action.attendantName')}}出发前全部服务退款将退还
						</view>
					</view>
					<view>¥{{detail.car_price}}</view>
				</view>
			</view>
			<view class="mt-lg pt-lg f-paragraph c-title flex-between b-1px-t">
				<view>合计</view>
				<view class="f-title c-warning text-bold">
					{{`${can_refund_price}元`}}
				</view>
			</view>
		</view>
		<view class="item-child mt-md ml-lg mr-lg pd-lg fill-base radius-16">
			<view class="flex-between pb-lg f-title c-title text-bold">退款原因</view>
			<view @tap.stop="toRefundItem(index)" class="flex-center mb-lg" v-for="(item,index) in refundList"
				:key="index">
				<i class="iconfont" :class="[{'icon-xuanze':refundInd!=index},{'icon-radio-fill':refundInd==index}]"
					:style="{color:refundInd==index?primaryColor:'#BEC3CE'}"></i>
				<view class="f-paragraph flex-1 ml-md" style="color: #0F0D0E;">{{item}}</view>
			</view>
			<view class="textarea-info f-caption c-caption radius-16" v-if="refundInd==4">
				<textarea v-model="form.text" class="input-textarea f-paragraph pd-lg" placeholder-class="f-paragraph"
					maxlength="300" placeholder="输入退款原因" />
				<view class="text-right pb-lg pr-lg">{{form.text.length>300?300:form.text.length}}/300</view>
			</view>
		</view>
		<view class="item-child mt-md ml-lg mr-lg pt-lg pl-lg pr-lg fill-base radius-16">
			<view class="flex-between pb-sm f-title c-title text-bold">上传图片</view>
			<view class="flex-between pt-md">
				<upload @del="imgDel" @upload="imgUpload" :imagelist="form.imgs" imgtype="imgs" imgclass="mini"
					text="添加照片" :imgsize="5"></upload>
			</view>
			<view class="space-lg" v-if="form.imgs.length == 0"></view>
			<view class="space-sm" v-else></view>
		</view>

		<view class="item-child mt-md ml-lg mr-lg pd-lg fill-base radius-16">
			<view class="flex-between pb-lg f-title c-title text-bold">退款须知</view>
			<parser :html="configInfo.trading_rules" @linkpress="linkpress" show-with-animation lazy-load>
				加载中...
			</parser>
		</view>

		<view class="space-max-footer"></view>

		<view class="refund-bottom-info fill-base fix pl-lg pr-lg">
			<view class="flex-between">
				<view @tap="selectAllItem" class="flex-y-center mr-lg"><i class="iconfont mr-sm"
						:class="[{'icon-xuanze':!selectAll},{'icon-xuanze-fill':selectAll}]"
						:style="{color:selectAll? primaryColor : ''}"></i>
					全选
				</view>
				<view class="count-info"
					:class="[{'text-right flex-center':total_empty_refund_cash*1==0},{'flex-between flex-1':total_empty_refund_cash*1>0}]">
					<view class="flex-between flex-1" v-if="total_empty_refund_cash*1">
						<view>
							<view class="flex-y-baseline">
								退款金额<view class="flex-y-baseline f-caption c-warning">¥<view class="f-title text-bold">
										{{total_refund_price}}
									</view>
								</view>
							</view>
							<view class="f-caption c-caption mr-sm">共{{total_refund_num}}件</view>
						</view>
						<view @tap.stop="$refs.empty_order_item.open()" class="empty-info flex-center f-caption"
							style="color:#19293F">扣费明细<i class="iconfont iconshaixuanxia-1"
								style="font-size: 20rpx;color:#BFBFBF;transform: scale(0.5);"></i></view>
					</view>
					<view class="flex-y-center" v-else>
						<view class="f-caption c-caption mr-sm">共{{total_refund_num}}件</view>
						退款金额<view class="flex-y-baseline f-caption c-warning">¥<view class="f-title text-bold">
								{{total_refund_price}}
							</view>
						</view>
					</view>
					<button @tap.stop="toSubmit" class="clear-btn order"
						:style="{color:'#fff',background:primaryColor,borderColor:primaryColor}">提交申请</button>
				</view>
			</view>
			<view class="space-safe"></view>
		</view>




		<uni-popup ref="empty_order_item" type="bottom" radius="0rpx">
			<view class="fill-base" style="padding:60rpx 30rpx">
				<view class="flex-center f-md-title" style="color: #19293F;height:42rpx">扣费明细</view>
				<i @tap.stop="$refs.empty_order_item.close()" class="iconfont icon-close c-caption abs"
					style="font-size: 36rpx;top:62rpx;right:30rpx"></i>
				<view class="flex-between" style="margin-top: 117rpx;">
					<view style="font-size: 34rpx;color: #19293F;">扣费合计</view>
					<view class="f-title" style="color: #F1381F;">¥{{total_empty_refund_cash}}</view>
				</view>
				<view class="flex-between f-desc mt-lg" style="color:#72747A"
					v-if="total_refund_num == can_refund_num && detail.pay_type ==5&&detail.empty_order_cash*1>0">
					<view>空单费</view>
					<view>¥{{detail.empty_order_cash}}</view>
				</view>
				<block v-if="refund_order_cash*1>0">
					<view class="flex-between f-desc mt-lg" style="color:#72747A">
						<view>服务扣费</view>
						<view>¥{{refund_order_cash}}</view>
					</view>
					<view class="flex-between f-desc" style="color:#72747A">
						<view></view>
						<view>服务费的{{refund_balance}}%</view>
					</view>
				</block>
				<view class="space-safe"></view>
			</view>
		</uni-popup>

	</view>
</template>

<script>
	import {
		mapState,
		mapActions,
		mapMutations
	} from "vuex"
	import parser from "@/components/jyf-Parser/index"
	export default {
		components: {
			parser
		},
		data() {
			return {
				options: {},
				detail: {},
				statusType: {
					'-1': '已取消',
					1: '待支付',
					2: '待服务',
					3: this.$t('action.attendantName') + '接单',
					4: this.$t('action.attendantName') + '出发',
					5: this.$t('action.attendantName') + '到达',
					6: '服务中',
					7: '已完成',
					8: '已评价',
				},
				refundList: ['临时有事,地址填写错误', `${this.$t('action.attendantName')}未按时服务`,
					`${this.$t('action.attendantName')}由于上单加钟无法服务`, `下单后${this.$t('action.attendantName')}未主动联系`,
					'其他原因'
				],
				refundInd: 0,
				total_refund_num: 0,
				total_refund_price: 0,
				can_refund_num: 0,
				can_refund_price: 0,
				selectAll: false,
				selectAdd: false,
				form: {
					text: '临时有事,地址填写错误',
					imgs: []
				},
				lockTap: false,
				refund_balance: '',
				refund_order_cash: '',
				total_empty_refund_cash: 0,
				timer: null
			}
		},
		computed: mapState({
			configInfo: state => state.config.configInfo,
		}),
		onLoad(options) {
			this.options = options
			this.initIndex()
		},
		// #ifdef H5
		destroyed() {
			// #endif
			// #ifndef H5
			onUnload() {
					// #endif
					if (this.timer) clearInterval(this.timer)
				},
				methods: {
					...mapActions(['getConfigInfo']),
					...mapMutations(['updateUserItem', 'updateOrderItem']),
					async initIndex(refresh = false) {
						let {
							id
						} = this.options
						let [data] = await Promise.all([this.$api.order.orderInfo({
							id,
							apply_refund: 1
						}), this.getConfigInfo({
							rules_status: 1
						})])
						this.$util.setNavigationBarColor({
							bg: this.primaryColor
						})

						let {
							car_price,
							free_fare,
							can_refund_car_price = 0,
							can_refund = 0,
							pay_type,
							start_service_time,
							refund_cash_list,
							empty_order_cash
						} = data
						empty_order_cash = pay_type != 5 ? 0 : empty_order_cash
						data.empty_order_cash = empty_order_cash



						let refund_balance = 0
						if (pay_type > 5 && refund_cash_list.length > 0) {
							let unix = this.$util.DateToUnix(this.$util.formatTime(new Date(), 'YY-M-D h:m:s'))
							let start_unix = this.$util.DateToUnix(start_service_time)
							let minute = Math.ceil((unix - start_unix) / 60)
							let arr = refund_cash_list.filter(item => {
								return item.minute >= minute
							})
							let {
								balance
							} = arr && arr.length > 0 ? arr[0] : {
								balance: 0
							}
							refund_balance = balance
							if (arr.length == 0) {
								can_refund = 0
							}
						}
						this.refund_balance = refund_balance


						if (!can_refund) {
							this.$util.showToast({
								title: `当前订单不支持退款哦`
							})
							setTimeout(() => {
								this.$util.back()
								if (this.$util.getPage(-1).detail) {
									this.$util.getPage(-2).initRefresh()
								}
								this.$util.goUrl({
									url: 1,
									openType: `navigateBack`
								})
							}, 2000)
							return
						}



						let num = 0
						let can_refund_price = 0
						data.order_goods.map(item => {
							num += item.can_refund_num
							item.apply_num = item.can_refund_num
							item.checked = item.can_refund_num < 1
							if (item.apply_num > 0) {
								can_refund_price += item.true_price * item.apply_num
							}
						})
						let total_price = (can_refund_price * 1).toFixed(2)
						data.can_refund_price = total_price
						this.detail = data
						this.can_refund_num = num
						let car_total_price = can_refund_car_price && !free_fare ? car_price : 0
						this.can_refund_price = (total_price * 1 + car_total_price * 1).toFixed(2)
						let can_refund_goods = data.order_goods.filter(item => {
							return item.can_refund_num > 0
						})
						if (can_refund_goods.length == 1) {
							this.selectAllItem()
						}
						if (pay_type > 5) {
							this.timer = setInterval(() => {
								this.countPrice()
							}, 60000)
						}
						// #ifdef H5
						if (!refresh) {
							this.$jweixin.hideOptionMenu()
						}
						// #endif
					},
					initRefresh() {
						this.initIndex(true)
					},
					imgDel(e) {
						let {
							imagelist,
							imgtype
						} = e;
						this.form[imgtype] = imagelist;
					},
					imgUpload(e) {
						let {
							imagelist,
							imgtype
						} = e;
						this.form[imgtype] = imagelist;
					},
					linkpress(res) {
						// #ifdef APP-PLUS
						this.$util.goUrl({
							url: res.href,
							openType: 'web'
						})
						// #endif
					},
					toRefundItem(index) {
						let text = this.refundList[index]
						this.refundInd = index
						this.form.text = index == 4 ? '' : text
					},
					handerRadioChange(index) {
						let item = this.detail.order_goods[index];
						if (item.can_refund_num < 1) return
						let newChecked = !item.checked;
						this.detail.order_goods[index].checked = newChecked;
						this.checkIsSelectAll();
					},
					handerAddRadioChange() {
						let {
							add_price
						} = this.detail
						if (!add_price * 1) return
						this.selectAdd = !this.selectAdd
						this.checkIsSelectAll()
					},
					async changeNum(index, mod) {
						let item = this.detail.order_goods[index];
						let num = item.apply_num + mod;
						if (num < 1) {
							this.$util.showToast({
								title: `此商品最少可退1件`
							})
							return;
						}
						if (num > item.can_refund_num) {
							this.$util.showToast({
								title: `此商品最多可退${item.can_refund_num}件`
							})
							return;
						}
						this.detail.order_goods[index].apply_num = num;
						this.countPrice();
					},
					selectAllItem() {
						this.detail.order_goods.map((item) => {
							if (item.can_refund_num < 1) return
							item.checked = !this.selectAll
						})
						this.checkIsSelectAll();
					},
					async checkIsSelectAll() {
						let list = []
						this.detail.order_goods.map(item => {
							if (item.can_refund_num < 1) return
							list.push(item)
						})
						this.selectAll = list.every((item) => {
							return item.checked
						})
						this.countPrice();
					},
					countPrice() {
						let {
							can_refund_num
						} = this
						let {
							car_price,
							free_fare,
							can_refund_car_price = 0,
							can_refund = 0,
							empty_order_cash,
							pay_type,
							start_service_time,
							refund_cash_list
						} = this.detail
						let price = 0
						let num = 0
						let list = []
						this.detail.order_goods.forEach(item => {
							if (item.can_refund_num < 1) return
							list.push(item)
						})

						let refund_balance = 0
						if (pay_type > 5 && refund_cash_list.length > 0) {
							let unix = this.$util.DateToUnix(this.$util.formatTime(new Date(), 'YY-M-D h:m:s'))
							let start_unix = this.$util.DateToUnix(start_service_time)
							let minute = Math.ceil((unix - start_unix) / 60)
							let arr = refund_cash_list.filter(item => {
								return item.minute >= minute
							})
							let {
								balance
							} = arr && arr.length > 0 ? arr[0] : {
								balance: 0
							}
							refund_balance = balance
							if (arr.length == 0) {
								can_refund = 0
							}
						}
						this.refund_balance = refund_balance


						if (!can_refund) {
							this.$util.showToast({
								title: `当前订单不支持退款哦`
							})
							setTimeout(() => {
								this.$util.back()
								if (this.$util.getPage(-1).detail) {
									this.$util.getPage(-2).initRefresh()
								}
								this.$util.goUrl({
									url: 1,
									openType: `navigateBack`
								})
							}, 2000)
							return
						}

						let refund_order_cash = 0
						list.forEach((item, index) => {
							if (item.checked) {
								if (refund_balance) {
									refund_order_cash += (item.true_price * refund_balance / 100 * item.apply_num)
										.toFixed(
											2) * 1
								}
								price += parseFloat(item.true_price * 1) * item.apply_num;
								num += item.apply_num
							}
						})
						this.refund_order_cash = (refund_order_cash * 1).toFixed(2)

						let total_price = price.toFixed(2) * 1
						let isAll = can_refund_num == num
						car_price = can_refund_car_price && isAll && !free_fare ? car_price : 0
						this.total_refund_num = num
						let total_refund_price = (total_price + car_price * 1 - refund_order_cash * 1).toFixed(2)
						if (isAll && pay_type == 5) {
							empty_order_cash = total_refund_price * 1 < empty_order_cash * 1 ? total_refund_price :
								empty_order_cash
							total_refund_price = (total_refund_price * 1 - empty_order_cash * 1).toFixed(2)
							this.detail.empty_order_cash = empty_order_cash
						}
						this.total_refund_price = total_refund_price * 1 > 0 ? total_refund_price : 0

						let refund_empty = pay_type == 5 && isAll ? empty_order_cash : 0
						let allRefundCash = (refund_order_cash * 1 + refund_empty *
							1).toFixed(2)
						this.total_empty_refund_cash = allRefundCash % 1 == 0 ? allRefundCash : this.$util
							.formatDecimalText(allRefundCash)
					},
					// 提交申请
					async toSubmit() {
						let {
							id: order_id,
							order_goods,
							pay_type
						} = this.detail
						let list = []
						order_goods.filter(item => {
							if (item.checked) {
								if (item.apply_num < 1) return
								list.push({
									id: item.id,
									num: item.apply_num
								})
							}
						})
						if (list.length < 1) {
							this.$util.showToast({
								title: `请选择商品`,
							});
							return
						}
						if (pay_type > 5) {
							await this.checkIsSelectAll()
						}
						let param = this.$util.deepCopy(this.form)

						let order_text = param.text.replace(/(^\s*)|(\s*$)/g, "")
						if (!order_text) {
							this.$util.showToast({
								title: `请输入退款原因`,
							});
							return
						}
						param.imgs = param.imgs.length > 0 ? param.imgs.map(item => {
							return item.path
						}) : []
						param = Object.assign({}, param, {
							order_id,
							list
						})

						if (this.lockTap) return
						this.lockTap = true
						this.$util.showLoading()
						try {
							await this.$api.order.applyOrder(param)
							this.$util.hideAll()
							this.$util.showToast({
								title: `提交成功`,
							});
							this.lockTap = false
							this.updateOrderItem({
								key: 'haveOperItem',
								val: true
							})
							setTimeout(() => {
								this.$util.goUrl({
									url: 1,
									openType: `navigateBack`
								})
							}, 1000)
						} catch (e) {
							setTimeout(() => {
								this.lockTap = false
								this.$util.hideAll()
							}, 2000)
						}
					},
				}
		}
</script>


<style lang="scss">
	.user-order-refund {


		.item-child {

			.icon-xuanze,
			.icon-xuanze-fill,
			.icon-radio-fill {
				font-size: 38rpx;
			}

			.goods-img {
				width: 155rpx;
				height: 155rpx;
			}

			.goods-spe {
				height: 44rpx;
				line-height: 44rpx;
				background: #F7F7F7;
			}

			.goods-num {
				width: 200rpx;
			}


			.textarea-info {
				background: #F7F7F7;

				.input-textarea {
					width: 570rpx;
					height: 150rpx;
				}
			}


		}

		.refund-bottom-info {
			bottom: 0;

			.iconfont {
				font-size: 38rpx;
			}

			.count-info {
				height: 110rpx;

				.order {
					margin-top: 0;
					border-radius: 30rpx;
				}
			}

		}
	}
</style>